﻿using LPP.Entity.AppUser;
using LPP.Entity.RegisterRequest;
using LPP.Service;
using LPP.Service.UserRepository;
using Microsoft.AspNetCore.Mvc;
using LPP.Core.Jwt;
using System.Security.Claims;
using Microsoft.Extensions.Logging;
using LPP.Entity;
using LPP.Service.SmsService;
using System.ComponentModel.DataAnnotations;

namespace LPP.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly TokenManagement _tokenManagement;
        private readonly ILogger<UserController> _logger;

        public UserController(
            IUserService userService,
            TokenManagement tokenManagement,
            ILogger<UserController> logger)
        {
            _userService = userService;
            _tokenManagement = tokenManagement;
            _logger = logger;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] UserRegisterRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { message = "请检查输入数据" });
                }

                // 检查手机号是否已注册
                var existingUser = await _userService.GetUserByPhoneNumberAsync(request.PhoneNumber);
                if (existingUser != null)
                {
                    return BadRequest(new { message = "该手机号已注册" });
                }

                // 创建新用户
                var user = new Users
                {
                    PhoneNumber = request.PhoneNumber,
                    CreatedAt = DateTime.UtcNow,
                    IsDelete = false
                };

                await _userService.CreateUserAsync(user);

                // 生成 Token
                var token = GenerateJwtToken(user.UserID, user.PhoneNumber);

                return Ok(new
                {
                    userId = user.UserID,
                    token,
                    message = "注册成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户注册失败");
                return StatusCode(500, new { message = "注册失败，请稍后重试" });
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] UserLoginRequest request)
        {
            try
            {
                var user = await _userService.GetUserByPhoneNumberAsync(request.PhoneNumber);
                if (user == null)
                {
                    return NotFound(new { message = "用户不存在" });
                }

                if (user.IsDelete)
                {
                    return BadRequest(new { message = "账号已被禁用" });
                }

                // 生成新的 Token
                var token = GenerateJwtToken(user.UserID, user.PhoneNumber);

                return Ok(new
                {
                    userId = user.UserID,
                    token,
                    message = "登录成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户登录失败");
                return StatusCode(500, new { message = "登录失败，请稍后重试" });
            }
        }

        /// <summary>
        /// 软删除用户
        /// </summary>
        [HttpDelete("{userId}")]
        public async Task<IActionResult> DeleteUser(int userId)
        {
            try
            {
                var user = await _userService.GetUserByIdAsync(userId);
                if (user == null)
                {
                    return NotFound(new { message = "用户不存在" });
                }

                // 执行软删除
                user.IsDelete = true;
                await _userService.UpdateUserAsync(user);

                return Ok(new { message = "用户已禁用" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除用户失败");
                return StatusCode(500, new { message = "操作失败，请稍后重试" });
            }
        }

        #region 私有方法

        private string GenerateJwtToken(int userId, string phoneNumber)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Sid, userId.ToString()),
                new Claim(ClaimTypes.Name, phoneNumber)
            };
            return JwtHelper.CreateToken(claims, _tokenManagement);
        }

        #endregion
    }

    /// <summary>
    /// 统一的API响应格式
    /// </summary>
    public class ApiResponse<T>
    {
        public bool Success { get; set; }
        public string Message { get; set; }
        public T Data { get; set; }
    }

    public class UserRegisterRequest
    {
        [Required(ErrorMessage = "手机号是必填项")]
        [Phone(ErrorMessage = "请输入有效的手机号")]
        public string PhoneNumber { get; set; }
    }

    public class UserLoginRequest
    {
        [Required(ErrorMessage = "手机号是必填项")]
        [Phone(ErrorMessage = "请输入有效的手机号")]
        public string PhoneNumber { get; set; }
    }
}
